/**
 * 
 */
package dms.service.imp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import dms.model.role.Account;
import dms.repository.AccountRepository;
import dms.service.AuthenticationService;
import dms.util.Constant;
import dms.util.PasswordUtil;

/**
 * @author 李健
 *
 */
public class AuthenticationServiceImpl implements AuthenticationService {

	private AccountRepository accountRepository = null;
	
	public AuthenticationServiceImpl() {}
	
	@Override
	public boolean checkAuthentication(String name, String password) {
		Account account = this.accountRepository.findAccountByName(name);
		
		if (account == null) {
			//throw new UserNotFoundException("没有该用户");
			return false;
		}
		
		String encryptPassword = PasswordUtil.MD5Digest(password);
		if (!account.getPassword().equals(encryptPassword)) {
			//throw new ErrorPasswordException("密码错误");
			return false;
		}
		
		return true;
	}

	@Override
	public boolean forgetPassword(long id, String passwordAnswer) {
		Account account = this.accountRepository.findAccountById(id);
		if (account.getPasswordAnswer().equals(passwordAnswer)) {
			//TODO随机重设该用户密码，并发送到邮箱
			return true;
		} else {
			return false;
		}
		
	}

	@Override
	public boolean forgetPassword(String name, String passwordAnswer) {
		Account account = this.accountRepository.findAccountByName(name);
		if (account.getPasswordAnswer().equals(passwordAnswer)) {
			//TODO随机重设该用户密码，并发送到邮箱
			return true;
		} else {
			return false;
		}
		
	}

	@Override
	public boolean isLogin(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return false;
		}
		
		Account account = (Account) session.getAttribute(Constant.ACCOUNT);
		if (account == null) {
			return false;
		} 
		
		return true;
	}

	@Override
	public boolean isUserExist(String name) {
		Account account = this.accountRepository.findAccountByName(name);
		if (account == null) {
			return false;
		}
		return true;
	}

	/**
	 * @return the accountRepository
	 */
	public AccountRepository getAccountRepository() {
		return accountRepository;
	}

	/**
	 * @param accountRepository the accountRepository to set
	 */
	public void setAccountRepository(AccountRepository accountRepository) {
		this.accountRepository = accountRepository;
	}

	/**
	 * @param accountRepository
	 */
	public AuthenticationServiceImpl(AccountRepository accountRepository) {
		super();
		this.accountRepository = accountRepository;
	}

}
